package design.structure_combination;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 组合模式（模拟spring中WebMvcConfigurerComposite进行演示）
 * @Auther: luobiao
 * @Date: 2021/1/24 10:43
 * @Description:
 */
public class DemoCombination {
    @Test
    public void test(){
        DelegatingWebMvcConfiguration delegatingWebMvcConfiguration=new DelegatingWebMvcConfiguration();
        //spring中是通过@Autowrite进行注入自定义WebMvcConfigurer配置的，此处手动设置
        //DelegatingWebMvcConfiguration内部持有WebMvcConfigurerComposite对象的引用，WebMvcConfigurerComposite本身也是个WebMvcConfigurer对象
        //只不过它的addInterceptors方法是循环执行内部WebMvcConfigurer对象列表的addInterceptors方法
        delegatingWebMvcConfiguration.setConfigurers(Arrays.asList(new MyWebMvcConfigurer1(),new MyWebMvcConfigurer2()));
        delegatingWebMvcConfiguration.addInterceptors(new InterceptorRegistry());
    }

    public interface WebMvcConfigurer{
        void addInterceptors(InterceptorRegistry register);
    }

    public class MyWebMvcConfigurer1 implements WebMvcConfigurer{
        @Override
        public void addInterceptors(InterceptorRegistry register) {
            register.addInterceptor("MyWebMvcConfigurer1 自定义拦截器");
        }
    }

    public class MyWebMvcConfigurer2 implements WebMvcConfigurer{
        @Override
        public void addInterceptors(InterceptorRegistry register) {
            register.addInterceptor("MyWebMvcConfigurer2 自定义拦截器");
        }
    }

    public class WebMvcConfigurerComposite implements WebMvcConfigurer{
        private List<WebMvcConfigurer> configurers = new ArrayList<>();

        public void addWebMvcConfigurers(List<WebMvcConfigurer> configurers){
            this.configurers.addAll(configurers);
        }

        @Override
        public void addInterceptors(InterceptorRegistry register) {
            configurers.stream().forEach(l->l.addInterceptors(register));
        }
    }

    public class DelegatingWebMvcConfiguration{
        private WebMvcConfigurerComposite configurerComposite = new WebMvcConfigurerComposite();
        public void setConfigurers(List<WebMvcConfigurer> list) {
            configurerComposite.addWebMvcConfigurers(list);
        }
        public void addInterceptors(InterceptorRegistry register){
            configurerComposite.addInterceptors(register);
        }
    }

    public class InterceptorRegistry{
        List<String> interceptorList = new ArrayList<>();
        public void addInterceptor(String interceptorName){
            interceptorList.add(interceptorName);
            System.out.println("添加拦截器"+interceptorName+"到拦截器链");
        }
    }

}
